package com.zxy.furns.web;/**
 * ClassName: OrderServlet
 * Package: com.zxy.furns.web
 *
 * @Author zxy
 * @Create 2025/3/26 0:11
 * @Version 1.0
 * title:
 * Description:
 */

import com.zxy.furns.entity.Cart;
import com.zxy.furns.entity.Member;
import com.zxy.furns.entity.Order;
import com.zxy.furns.entity.OrderItem;
import com.zxy.furns.service.OrderService;
import com.zxy.furns.service.impl.OrderServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;

@WebServlet("/orderServlet")
public class OrderServlet extends BasicServlet {
    private OrderService orderService = new OrderServiceImpl();

    protected void saveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart == null || cart.getItems().isEmpty()) {
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        //获取当前member对象
        Member member = (Member) req.getSession().getAttribute("member");
        if (member == null) {
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
            return;
        }

        String orderId = orderService.saveOrder(cart, member.getId());
        req.getSession().setAttribute("orderId", orderId);
        resp.sendRedirect(req.getContextPath() + "/views/order/checkout.jsp");
    }


    protected void orderList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Member member = (Member) req.getSession().getAttribute("member");
        if (member == null) {
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
            return;
        }
        List<Order> orders = orderService.listOrder(member.getId());
        req.getSession().setAttribute("orders", orders);
        req.getRequestDispatcher("/views/order/order.jsp").forward(req, resp);
    }

    protected void orderItemList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderId = req.getParameter("orderId");
        System.out.println("拿到的orderId = " + orderId);
        //获取当前登录的memberId
        Member member = (Member) req.getSession().getAttribute("member");
        if (member == null) {
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }
        List<OrderItem> orderItems = orderService.listOrderItem(orderId);
        req.getSession().setAttribute("orderItems", orderItems);
        req.getSession().setAttribute("orderId", orderId);

        //请求转发到order_detail.jsp
        req.getRequestDispatcher("/views/order/order_detail.jsp").forward(req, resp);
    }
}